class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution(object):
    def preorderTraversal(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        output_list = []
        if not root:
            return output_list
        stack = [root]
        output_list = [root.val]
        while stack:
            if stack[-1].left:
                stack.append(stack[-1].left)
                output_list.append(stack[-1].val)
            else:
                while stack:
                    node = stack.pop()
                    if node.right:
                        stack.append(node.right)
                        output_list.append(stack[-1].val)
                        break
        return output_list